package com.tvunetworks.center.user.service.impl;

import com.github.pagehelper.PageInfo;
import com.tvunetworks.center.common.model.PageUserDeviceParam;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.gs.model.Device;
import com.tvunetworks.center.user.model.User;
import com.tvunetworks.center.user.service.UserDeviceService;
import com.tvunetworks.center.user.service.UserFeignService;
import com.tvunetworks.center.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Etan Yang
 * @data: 2021/6/4 19:05
 * @program: tvucc-aggregator
 * @description:
 */

@Slf4j
@Service
public class UserFeignServiceImpl implements UserFeignService {
    @Autowired
    private UserDeviceService userDeviceService;
    @Autowired
    private UserService userService;


    @Override
    public PageInfo<Device> pageUserDevice(PageUserDeviceParam param) {
        int pageNum = param.getPageNum();
        int pageSize = param.getPageSize();
        if (pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        List<Device> devices = userDeviceService.listUserDevice(param);
        int index = (pageNum - 1) * pageSize;
        if (CollectionUtils.isEmpty(devices)) {
            return new PageInfo<>();
        }
        List<Device> result = devices.stream().skip(index).limit(pageSize).collect(Collectors.toList());
        PageInfo<Device> pageInfo = new PageInfo<>(result);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(devices.size());
        return pageInfo;
    }

    @Override
    public Result<Integer> getRoleByEmail(String email) {
        User user = userService.getByEmail(email);
        int role = 0;
        if (user != null) {
            String userRole = user.getRole();
            role = StringUtils.isEmpty(userRole) ? 0 : Integer.parseInt(userRole);
        }
        return ResultUtil.success(role);
    }

}
